package com.ly.mpayment.rest.up.shuwang;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Path("shuwang")
public class ShuWangRest {
    Logger logger = Logger.getLogger(ShuWangRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @GET
    public String callBack(@QueryParam("agtPhone") String agtPhone,@QueryParam("reqStreamId") String reqStreamId,
                           @QueryParam("state") String state,@QueryParam("sign") String sign) {
        logger.info("shuwang_callback:" + reqStreamId+",state:"+state);
        if (!StringUtils.isBlank(reqStreamId)) {
            UpOrder order = upOrderService.findById(reqStreamId);
            if(order == null){
                logger.info("订单不存在:"+reqStreamId);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+reqStreamId);
                return "1";
            }

            //userid=xxxx&orderid=xxxxxxx&sporderid=xxxxx&merchantsubmittime=xxxxx&resultno=xxxxx&key=xxxxxxx (这里的xxxxx为具体的参数值)
            if(!sign.equalsIgnoreCase(MD5.md5(agtPhone+reqStreamId+state+upShopInfo.getUpkey()))){
                logger.info("签名错误:"+reqStreamId);
                return "1";
            }

            if (order != null && state.equals("0") && order.getStatus() == Config.status[0]) {
                order.setRemark(state);
                RechargeRest.successUpOrder.add(order);
                return "0";
            } else if (order != null && order.getStatus() == Config.status[0] && state.equals("1")) {
                order.setRemark(state);
                RechargeRest.failtUpOrder.add(order);
                return "0";
            } else {
                this.upOrderService.addOrderMsg(order,state);
                logger.info("shuwang_not_found_order:" + reqStreamId + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("reqStreamNo", order.getUporderuuid());
        data.put("accountNo", shop.getAppId());
        data.put("business", order.getUpShopPro().getProductCode());
        data.put("phone", order.getUpphonenum());
        data.put("face", order.getUpShopPro().getUpfacevalue());
        data.put("password", MD5.md5("22222222"));
        data.put("timeStamp", new DateUtils().toTimeStamp());

        //MD5(reqStreamNo+accountNo+business+phone+face+password+ timeStamp +key)32位小写
        data.put("sign", MD5.md5(  order.getUporderuuid() + shop.getAppId()+
                order.getUpShopPro().getProductCode()+ order.getUpphonenum()+ order.getUpShopPro().getUpfacevalue()+
                data.getString("password")+data.getString("timeStamp")+shop.getUpkey()));

        data.put("notify", shop.getOrderCallAddress());
        String result = HttpClient.httpGetUrl(shop.getOrderCommitAddress()+"?"+ StringSort.jsonToString(data));
        logger.info("commitOrder_shuwang:" + result + ":" + StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = JSONObject.parseObject(result);
                logger.info("commitOrder_shuwang_json:" + json);
                if (json.containsKey("status") && (json.getString("status").equals("0") || json.getString("status").equals("10"))) {
                    this.upOrderService.updateUpOrderMsg(order,json.getJSONObject("data").getString("orderId"),json.containsKey("msg") ?
                            json.getString("msg") : "");
                } else if (json.containsKey("status") && errorCode.contains(json.getString("status"))){
                    order.setRemark(json.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.addOrderMsg(order, json.getString("msg"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrder(order, "");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    /**
     * 0	提交成功
     * 1	提交失败（失败处理）
     * 2	请求方充值流水号重复（失败处理）
     * 4	交易密码错误（失败处理）
     * 5	代理号不存在（失败处理）
     * 6	余额不足（失败处理）
     * 7	业务关闭（失败处理）
     * 8	产品已下架（失败处理）
     * 9	号码问题无法充值（失败处理）
     * 10	提交成功
     */
    Set<String> errorCode = new HashSet<String>(){{
        add("1");
        add("2");
        add("4");
        add("5");
        add("6");
        add("7");
        add("8");
        add("9");
        add("11");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("reqStreamNo", upOrder.getUporderuuid());
        data.put("accountNo", shopInfo.getAppId());
        data.put("sign", MD5.md5(upOrder.getUporderuuid()+ shopInfo.getAppId()+ shopInfo.getUpkey()));

        String result = HttpClient.httpGetUrl(shopInfo.getOrderStatusAddress() +"?"+ StringSort.jsonToString(data));
        logger.info("shuwangqueryOrder:" + StringSort.jsonToString(data) + ":" + result);
        if (!StringUtils.isBlank(result)) {
            try {
                JSONObject items = JSONObject.parseObject(result);
                logger.info("queryOrder_shuwang_json:" + items);

                if (items.containsKey("data") ) {
                    UpOrder order = upOrderService.findById(items.getJSONObject("data").getString("reqStreamNo"));
                    if (order != null && items.getString("status").equals("0") && order.getStatus() == Config.status[0]) {
                        order.setRemark( items.containsKey("status") ? items.getString("status") :
                                items.getString("status"));
                        RechargeRest.successUpOrder.add(order);
                    } else if (order != null && order.getStatus() == Config.status[0] && items.getString("status").equals("1") ) {
                        order.setRemark(items.getString("status"));
                        RechargeRest.failtUpOrder.add(order);
                    } else {
                        this.upOrderService.addOrderMsg(order,items.getString("status"));
                        logger.info("shuwang_not_found_order:" + order.getUpphonenum());
                    }
                } else {
                    logger.info("shuwang_not_found_order:" + upOrder.getUpphonenum());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
//    public static void main(String[] args) throws DocumentException {
//        JSONObject json = new JSONObject();
//        String result = "<?xml version=\"1.0\" encoding=\"GB2312\" ?> \n" +
//                " <order>\n" +
//                "  <orderid>XS090428000003</orderid>\n" +
//                "  <productid>3312</productid>\n" +
//                "  <num>1</num> \n" +
//                "  <ordercash>98.5</ordercash>\n" +
//                "  <productname> 广东移动100元直充</productname> \n" +
//                "  <sporderid>2009042800001</sporderid> \n" +
//                "  <mobile>13590101510</mobile>\n" +
//                "  <merchantsubmittime></merchantsubmittime>\n" +
//                "  <resultno>0</resultno>\n" +
//                "  <remark1>凭证号</remark1>\n" +
//                "  <fundbalance>100000</fundbalance>\n" +
//                "  </order>\n";
//        new shuwangRest().iterateNodes(DocumentHelper.parseText(result).getRootElement(),json);
//        System.out.println(json);
//    }

    /**
     * 遍历元素
     *
     * @param node
     *            元素
     * @param json
     *            将元素遍历完成之后放的JSON对象
     */
    @SuppressWarnings("unchecked")
    public void iterateNodes(Element node, JSONObject json) {
        // 获取当前元素的名称
        String nodeName = node.getName();
        // 判断已遍历的JSON中是否已经有了该元素的名称
        if (json.containsKey(nodeName)) {
            // 该元素在同级下有多个
            Object Object = json.get(nodeName);
            JSONArray array = null;
            if (Object instanceof JSONArray) {
                array = (JSONArray) Object;
            } else {
                array = new JSONArray();
                array.add(Object);
            }
            // 获取该元素下所有子元素
            List<Element> listElement = node.elements();
            if (listElement.isEmpty()) {
                // 该元素无子元素，获取元素的值
                if(!node.attributes().isEmpty()){
                    json.put(node.attribute(0).getValue(), node.getText());
                }else{
                    String nodeValue = node.getText();
                    array.add(nodeValue);
                    json.put(nodeName, array);
                }
                return;
            }
            // 有子元素
            JSONObject newJson = new JSONObject();
            // 遍历所有子元素
            for (Element e : listElement) {
                // 递归
                iterateNodes(e, newJson);
            }
            array.add(newJson);
            json.put(nodeName, array);
            return;
        }
        // 该元素同级下第一次遍历
        // 获取该元素下所有子元素
        List<Element> listElement = node.elements();
        if (listElement.isEmpty()) {
            // 该元素无子元素，获取元素的值
            if(!node.attributes().isEmpty()){
                json.put(node.attribute(0).getValue(), node.getText());
            }else{
                String nodeValue = node.getText();
                json.put(nodeName, nodeValue);
            }

            return;
        }
        // 有子节点，新建一个JSONObject来存储该节点下子节点的值
        JSONObject object = new JSONObject();
        // 遍历所有一级子节点
        for (Element e : listElement) {
            // 递归
            iterateNodes(e, object);
        }
        json.put(nodeName, object);
        return;
    }
}
